import CryptoJS, { AES, MD5 } from "crypto-js";

export class AesEncryption {
  private key;
  private iv;
  private mode = CryptoJS.mode.ECB;
  private padding = CryptoJS.pad.Pkcs7;

  constructor({ key, iv }: { key?: string; iv?: string } = {}) {
    if (key) {
      this.key = CryptoJS.enc.Utf8.parse(key);
    }
    if (iv) {
      this.iv = CryptoJS.enc.Utf8.parse(iv);
    }
  }

  encryptByAES(cipherText: string) {
    return AES.encrypt(cipherText, this.key!, { iv: this.iv, mode: this.mode, padding: this.padding }).toString();
  }

  decryptByAES(cipherText: string) {
    return AES.decrypt(cipherText, this.key!, { iv: this.iv, mode: this.mode, padding: this.padding }).toString(CryptoJS.enc.Utf8);
  }
}

export function encryptByBase64(cipherText: string) {
  return CryptoJS.enc.Utf8.parse(cipherText).toString(CryptoJS.enc.Base64);
}

export function decodeByBase64(cipherText: string) {
  return CryptoJS.enc.Base64.parse(cipherText).toString(CryptoJS.enc.Utf8);
}

export function encryptByMd5(password: string) {
  return MD5(password).toString();
}
